package com.angcyo.selenium.auto.action

import com.angcyo.library.ex.getLongNumList
import com.angcyo.selenium.auto.BaseControl
import com.angcyo.selenium.auto.findAction
import com.angcyo.selenium.auto.parse.HandleResult
import com.angcyo.selenium.bean.ActionBean
import org.openqa.selenium.WebElement

/**
 * Email:angcyo@126.com
 * @author angcyo
 * @date 2021-1-13
 */
class JumpAction : BaseAction() {

    override fun interceptAction(control: BaseControl, action: String?): Boolean {
        return action?.startsWith(Action.ACTION_JUMP) == true
    }

    override fun runAction(
        control: BaseControl,
        element: WebElement,
        actionBean: ActionBean,
        action: String
    ): HandleResult {
        val result = HandleResult()
        result.elementList = listOf(element)

        var jumpId = -1L

        if (action.arg(Action.ACTION_JUMP) == Action.RELY) {
            //跳过到依赖的action
            jumpId = jumpActionList(control, result, actionBean.relyList)
        } else {
            val actionIdList = action.getLongNumList(true)
            if (actionIdList == null) {
                //下一个
                control.actionSchedule.apply {
                    next()
                    result.success = nextActionBean != null
                    jumpId = nextActionBean?.actionId ?: jumpId
                }
            } else {
                //指定id
                jumpId = jumpActionList(control, result, actionIdList)
            }
        }

        if (result.success) {
            control.actionSchedule.jumpCountIncrement(actionBean.actionId)
        }

        control.logAction?.invoke("跳转至[${jumpId}]:${result.success}")
        return result
    }

    fun jumpActionList(control: BaseControl, result: HandleResult, actionIdList: List<Long>?): Long {
        var jumpId = -1L
        if (actionIdList != null) {
            for (actionId in actionIdList) {
                val findAction = control.findAction(actionId)
                if (findAction != null) {
                    jumpId = findAction.actionId
                    findAction.enable = true
                    control.actionSchedule.nextTarget(findAction)
                    result.success = true
                    break
                }
            }
        }
        return jumpId
    }
}